package com.bang.study.aggs;

import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.avg.InternalAvg;
import org.elasticsearch.search.aggregations.metrics.percentiles.Percentile;
import org.elasticsearch.search.aggregations.metrics.percentiles.tdigest.InternalTDigestPercentiles;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.util.Iterator;

/**
 * @ClassName: MuchAggsSearch
 * @author: BANG
 * @Date: 2020/01/15 16:57
 * @Version: 1.0
 * @Modified By:
 * @Desc: TODO
 *
 * GET /fs/file/_search
 * {
 *   "query": {
 *     "bool": {
 *       "must": [
 *         {
 *           "match": {
 *             "contents": "elasticsearch"
 *           }
 *         },
 *         {
 *           "constant_score": {
 *             "filter": {
 *               "term": {
 *                 "path": "/workspace/projects/helloworld"
 *               }
 *             }
 *           }
 *         }
 *       ]
 *     }
 *   }
 * }
 */
public class PathHierarchySearch {


    public static void main(String[] args) throws Exception {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("client.transport.sniff", true)
                .build();

        TransportClient client = new PreBuiltTransportClient(settings).addTransportAddress(
                new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300)
        );

        SearchResponse searchResponse = client.prepareSearch("fs").setTypes("file")
                .setQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.matchQuery("contents","elasticsearch"))
                        .must(QueryBuilders.constantScoreQuery(QueryBuilders.boolQuery()
                                .filter(QueryBuilders.termQuery("path.tree","/workspace"))))
                        )
                .get();
        SearchHit[] hits = searchResponse.getHits().getHits();
        for (SearchHit hit : hits) {
            System.err.println(hit.getSourceAsString());
        }


        client.close();

    }
}
